package com.project.lk.nurseapp.common.socket;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;


/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class SocketService extends Service {


    private String workStatus;// 当前工作状况，null表示正在处理，success表示处理成功，failure表示处理失败

    private String currAction; //标记当前请求头信息，在获取服务器端反馈的数据后，进行验证，以免出现反馈信息和当前请求不一致问题。比如现在发送第二个请求，但服务器端此时才响应第一个请求
    private Thread thread;
    /**心跳频率*/
    private static final long HEART_BEAT_RATE = 5 * 1000;
    private String hostname="";
    private String port="";

    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        super.onCreate();
        Log.e("MLOG", "Service Create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String socketAddress = intent.getStringExtra("socketAddress");
        Log.e("MLOG",socketAddress);
        String[] split = socketAddress.split(":");
        hostname = split[0];
        port = split[1];
        startSocket();

        return START_STICKY;
    }

    public void startSocket(){  //开启socket，
        thread = new Thread(){
            @Override
            public void run() {
                NIOSClient.getNIOSClient(hostname,port).setIPostExcetion(new NIOSClient.IPostExceptionInfo() {
                    @Override
                    public void postException() {
                        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//初始化成功后，就准备发送心跳包
                    }
                });
                mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//初始化成功后，就准备发送心跳包
                super.run();
            }
        };
        thread.start();
    }

    private Handler mHandler = new Handler();
    /**心跳任务，不断重复调用自己*/
    private Runnable heartBeatRunnable = new Runnable() {

        @Override
        public void run() {
                Log.e("MLOG",">>>>>SOCKET>>>>>>");
        //就发送一个\r\n过去 如果发送失败，就重新初始化一个socket
//            boolean  isConnSuccess=NIOSClient.getNIOSClient(SocketService.this).isConn;
            boolean   isSuccess = NIOSClient.getNIOSClient(hostname,port).sendMsg();
//            Log.e("MLOG",isConnSuccess+"=isConnSuccess,"+isSuccess+"=isSuccess");
            if (!isSuccess) {
                    mHandler.removeCallbacks(heartBeatRunnable);
                    startSocket();
                }
                if (isSuccess){
                    mHandler.postDelayed(this, HEART_BEAT_RATE);
                    mHandler.removeCallbacks(heartBeatRunnable);
                }

        }
    };

    /**
     * 销毁
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
//        myHandler=null;
        if (thread!=null) {
            thread.destroy();
        }
        Log.e("MLOG", "Service Destroy");
    }

    private final IBinder mBinder = new WsBinder();
    NotificationManager mNM;
    private static int NOTIFY_ID = 1000;
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private void initWebSocket(){

    }
    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }


public class WsBinder extends Binder {
    public SocketService getService() {
        return SocketService.this;
    }


}
    /***
     * 发送通知
     * @param context
     * @param title
     * @param contentText
     */
//    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
//    public static void sendNotification(Context context, String title, String contentText){
//        NotificationManager notifyMgr= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
//        Intent resultIntent = new Intent(context, MessageActivity.class);//MainActivity  GetMesgActivity
//        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        PendingIntent pi = PendingIntent.getActivity(context, 0,resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//        Notification notification = new Notification.Builder(context)
//                .setSmallIcon(R.mipmap.xw_header)
//                .setTicker("点击查看消息")
//                .setContentTitle(title)
//                .setContentText(contentText)
//                .setContentIntent(pi)
//                .setDefaults(Notification.DEFAULT_ALL)//DEFAULT_VIBRATE
//                .build();
//        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notifyMgr.notify(NOTIFY_ID, notification);
//    }

}
